<%@ page language="java" contentType="text/html; charset=utf-8"
    pageEncoding="utf-8"%>
<%@ taglib uri="http://tiles.apache.org/tags-tiles" prefix="tiles" %>
<%@ include file="/common/common.jsp" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>User Management</title>
<link rel="stylesheet" type="text/css" href="${rctx}/default/om-default.css" />
<style type="text/css">
.content-wrapper {
	width: 960px; 
	margin:0 auto 0;
	padding: 10px;
}
.formTb td{
	margin-bottom: 25px;
}	
.textarea_text {
	border: 1px solid #A1B9DF; 
	height: 40px;
	width: 100%;
}
</style>
<script type="text/javascript" src="${rctx}/operamasks-ui.min.js"></script>
<script type="text/javascript">
$(document).ready(function() {	
    $('#grid').omGrid({
        title : '系统用户表',
        dataSource : '${ctx}/auth/user/page?meth=1',
        colModel : [ {header : '用户名', name : 'username', width : 160, align : 'center'}, 
                     {header : '昵称', name : 'realname', width : 160, align : 'center'}, 
                     {header : 'e-mail', name : 'email',width: 120, align : 'center'},
                     {header : '是否启用', name : 'enabled',width: 60, align : 'center', renderer:genderRenderer},
                     {header : '备注', name : 'remark', align : 'left', width : 200},
                     {header : '详情', name : 'operation', width: "autoExpand", align:'center', renderer:function(colValue, rowData, rowIndex){
                    	 var data = rowData;
                    	 return '<button onClick="showUserRoleDialog('+rowIndex+',event)">修改角色</button>';
                     	}
                     }]
    });   
    
    $('input[name=enabled]').omCombo({          //初始化Combo
        dataSource : [ {text : '启用', value : 'true'}, 
                       {text : '停用', value : 'false'}],
        width : 150,
        value : 'false',
        editable:false,
    });
    
    $( "#dialog-modal").omDialog({
		autoOpen: false,
		width: 520,
		height: 290,
		modal: true,
		resizable: false
	});
    
    $( "#dialog-editUserRole").omDialog({
		autoOpen: false,
		width: 520,
		height: 290,
		modal: true,
		resizable: false
	});
    
    $("#mytree1").omTree({
        dataSource : "${ctx}/auth/role/findAllAsTree",
        simpleDataModel: true,
        showCheckbox:true,
        cascadeCheck:false
	});
    
    var options = {
            beforeSubmit : showRequest,
            success : showResponse,
            method : 'POST',
            clearForm: true
        };
 	//通过监听form的submit事件，对form进行ajax提交。
    $('#formId').submit(function() {
        if (!$("#formId").valid()) 
            return false;
        $(this).omAjaxSubmit(options);
        return false; //此处必须返回false，阻止常规的form提交。
    });
});
function genderRenderer(value){
    if(value){
        return "启用";
    } else {
        return "停用";
    }
}
function showRequest(formData, jqForm, options) {
    //var queryString = $.param(formData);
    //alert(queryString);
    return true;
}

function showResponse(responseText, statusText, xhr, $form) {
	var msg = responseText.error;
	showTopTip(msg);
	if($("#dialog-modal").omDialog('isOpen')) {
		$("#dialog-modal").omDialog('close');
	}
	$('#grid').omGrid('reload');
}
function showModelDialog(){
	$("#dialog-modal").omDialog('open');
}
function showTopTip(content){
    try{
        window.top.$.omMessageTip.show({
            title : '提醒',
            content : content,
            timeout : 5000
        });
    }catch(e){
        alert('提示失败！原因是：顶层页面没有引入提示所需要的js。');
    }
}
function rowToForm() {
	var selectedRecords = $('#grid').omGrid('getSelections',true);
	var record = selectedRecords[0];
	if (record == null) {showTopTip('请选择一条记录！');return false;}
	for (var p in record) { // 方法 
		if (typeof (record[p]) == " function ") {
			//record[p]();
		} else { // p 为属性名称，obj[p]为对应属性的值 
			$("[name='"+ p + "']", $("#formId")).val(record[p]);
		}
	}
	$('input[name=enabled]').omCombo('value',record.enabled);
	return true;
}
function deleteUser() {
	rowToForm();
    var options = {
            beforeSubmit : showRequest,
            success : showResponse,
            method : 'POST',
            clearForm: true,
            url : '${ctx}/auth/user/delete'
        };
	$("#formId").omAjaxSubmit(options);
}
function editUser() {
	if (rowToForm())
		showModelDialog();
}
function addUser() {
	$("#resetBtn").click();
	$('input[name=enabled]').omCombo('value','false');
	showModelDialog();
}
function showUserRoleDialog(index, event) {
	var data = $("#grid").omGrid("getData").rows[index];
	$("#mytree1").omTree('checkAll',false);	
	$.ajax({
		 type: "POST",
		  url: '${ctx}/auth/user/findUserRolesByUserId/'+data.id,
		  dataType: "json",
		  contentType: "application/json; charset=utf-8",
		  data: '',
		  success: function (data, textStatus) {
				var msg = data.error;
				var roles = data.resp;
				if (roles != null) {
					for (var i=0;i<roles.length;i++) {
						 var node = $('#mytree1').omTree('findNode', 'id', roles[i].role.id);
	                     $('#mytree1').omTree("check", node);
					}
				}
		  },
		  traditional: true
	});
	$("#dialog-editUserRole").omDialog('open');
}
function saveUserRole() {
	var id = $('#grid').omGrid('getSelections',true)[0].id;
	var roleid = $("#mytree1").omTree('getChecked',true);
	var req = {
		"user":{"id":id},
		"roles":roleid
	};
	
	$.ajax({
		  type: "POST",
		  url: '${ctx}/auth/user/saveUserRole',
		  dataType: "json",
		  contentType: "application/json; charset=utf-8",
		  data: JSON.stringify(req),
		  success: function (data, textStatus) {
				var msg = data.error;
				showTopTip(msg);
		  },
		  traditional: true
		});
	if($("#dialog-editUserRole").omDialog('isOpen')) {
		$("#dialog-editUserRole").omDialog('close');
	}
}
</script>
</head>
<body style="background-color: #2A2B2F;;margin: 0px">
<div id="back1" style="background-color: #00BFFF;width: 100%">
<div class="content-wrapper">
	<div id="btnBar" style="margin: 15px">
		<button id="addBtn" onclick="javascript: addUser();">添加</button>
		<button id="editBtn" onclick="javascript: editUser();">修改</button>
		<button id="deleteBtn" onclick="javascript: deleteUser();">删除</button>
	</div>	
    <div id="dialog-modal" title="维护数据">
    	<form id="formId" action="${ctx}/auth/user/save">
    	<input type="hidden" name="id">
    	<table id="formTb" class="formTb" cellspacing="15px">
    	<tr>
    	<td>用户名</td>
    	<td><input type="text" name="username"></td>
    	<td>昵称</td>
    	<td><input type="text" name="realname"></td>
    	</tr>
    	<tr>
    	<td>密码</td>
    	<td><input type="password" name="password"></td>  
    	<td>确认密码</td>
    	<td><input type="password" name="password2"></td>
    	</tr>
    	<tr>
    	<td>是否启用</td>
    	<td><input type="text" name="enabled"></td>  
    	<td>e-mail</td>
    	<td><input type="text" name="email"></td>
    	</tr>
    	<tr>
    	<td>备注</td>
    	<td colspan="3"><label>
	      	<textarea name="remark" class="textarea_text"></textarea></label></td>    	 
    	</tr>
    	<tr>
    		<td colspan="4" style="text-align: center;">
    			<button id="saveBtn" type="submit">保存</button>
    			<button id="resetBtn" type="reset">重置</button>
    		</td>
    	</tr>
    	</table>
    	</form>
    </div>
    <div id="dialog-editUserRole" title="修改角色">
    	<div style="height: 200px"><ul id="mytree1"></ul></div>
    	<div><button id="saveUserRoleBtn" onclick="javascript: saveUserRole();" type="submit">保存</button></div>
    </div>
</div>
</div>
<div id="back1" style="background-color: #FFFFFF;width: 100%">
<div class="content-wrapper">
	<table id="grid"></table>
</div>
</div>
</body>
</html>